package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {


    @Autowired
    private RabbitService rabbitService;

    @Override
    public void updatePaymentStatus(Transaction result) {
        //  修改交易记录状态。
        PaymentInfo paymentInfo = this.getOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, result.getOutTradeNo()));
        //  判断
        if (paymentInfo == null) return;
        //  修改支付状态
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        //  可以设置支付时间
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(result.toString());
        //  微信支付交易编号
        paymentInfo.setOutTradeNo(result.getTransactionId());
        this.updateById(paymentInfo);

        //  一个是订单状态，一个是充值状态！ 异步修改：
        if (paymentInfo.getPaymentType().equals(SystemConstant.PAYMENT_TYPE_ORDER)) {
            //  订单：
            rabbitService.sendMessage(MqConst.EXCHANGE_ORDER, MqConst.ROUTING_ORDER_PAY_SUCCESS, paymentInfo.getOrderNo());
        } else {
            //  充值：
            rabbitService.sendMessage(MqConst.EXCHANGE_ORDER, MqConst.ROUTING_RECHARGE_PAY_SUCCESS, paymentInfo.getOrderNo());
        }

    }

    @Override
    public void savePaymentInfo(Long userId, String paymentType, String orderNo, BigDecimal amount) {
        //  查询一下是否有重复的订单编号:
        PaymentInfo paymentInfo = this.getOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo, orderNo));
        if (null != paymentInfo) {
            return;
        }
        //  创建对象
        paymentInfo = new PaymentInfo();
        //  赋值
        paymentInfo.setUserId(userId);
        paymentInfo.setPaymentType(paymentType);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        paymentInfo.setAmount(amount);
        paymentInfo.setContent(paymentType.equals(SystemConstant.PAYMENT_TYPE_ORDER) ? "订单支付" : "充值");
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        //  保存交易记录
        this.save(paymentInfo);
    }
}
